import axios from "axios";
import router from "../router";
import Base64 from "../util/Base64";
import Cookie from "js-cookie";
import { login } from "../api/login";
import { Notification } from "element-ui";

let serve = axios.create({
  baseURL: "http://192.168.1.188:8080/m.api",
  timeout: 15000
});

// 添加请求拦截器
serve.interceptors.request.use(
  function(config) {
    // 在发送请求之前做些什么
    config.headers["AdminToken"] = Cookie.get("token"); //默认的意思
    return config;
  },
  function(error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);
//添加响应拦截器   //async异步引子
serve.interceptors.response.use(
  async response => {
    // 对响应数据做点什么
    if (response.data.errno == 10006 || response.data.errno == 10001) {
      if (router.currentRoute.name != "登录" && Cookie.get("username")) {
        let forms = {
          //传参的数值
          name: Base64.decode(Cookie.get("username")),
          pwd: Base64.decode(Cookie.get("userpwd")),
          code: 666666
        };
        await login(forms).then(res => {
          let Time = new Date(new Date().getTime() + 60 * 1000 * 20); //过期时间
          Cookie.set("token", res.data.data, { expires: Time }); //将令牌存储 并设置过期时间
        });
        return serve(response.config);
      } else {
        if (document.getElementsByClassName("el-message").length === 0) {
          //防止多次点击
          Notification.info({
            title: "消息",
            message: "长时间未操作 请重新登陆",
            type: "success",
            duration: "1300"
          });
        }
        Cookie.remove("token");
        setTimeout(
          () => router.push("/?returnUrl=" + router.currentRoute.path),
          200
        );
      }
    }
    return response;
  },
  error => {
    // 对响应错误做点什么

    return Promise.reject(error);
  }
);
export default serve;
